package org.grow.later.user;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Controller
public class Login {
    @PostMapping("/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if ("kitty".equals(username) && "1234".equals(password)){
            //JSP style
            ModelAndView successPage = new ModelAndView("success");
            successPage.addObject("username",username);
            successPage.addObject("relative",this.findRelativeByUsername("kitty"));
            return successPage;
        }
        else {
            String prefix = "<!DOCTYPE html>\n" +
                    "<html lang=\"en\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>failure</title>\n" +
                    "</head>\n" +
                    "<body>\n";
            String content = "<h2>username "+username+" or password is not correct ! </h2>";

            String suffix = "</body>\n" +
                    "</html>";

            PrintWriter writer = response.getWriter();
            writer.append(prefix);
            writer.append(content);
            writer.append(LocalDateTime.now().toString());
            writer.append(suffix);
            writer.flush();
            writer.close();
            return null;
        }

    }
    private List<Person> findRelativeByUsername(String username){
       if (username.equals("kitty")){
           Person father = new Person("Jack",55,"father");
           Person mother = new Person("Rose", 45, "mother");
           return Arrays.asList(father,mother);
       }
        return null;
    }


    @GetMapping("/user")
    public String userPage(){
        return "user";
    }

    @Resource
    private Logout logout;
    @ResponseBody
    @GetMapping("/totalReqNum")
    public String total(){
        Long accessAcount = logout.getAccessAccount();
        return "服务器处理的请求总数量: "+ accessAcount;
    }

}
